package com.iflytek.yly.jetpackdemo.viewmodel;

import androidx.lifecycle.ViewModel;

import java.util.Timer;
import java.util.TimerTask;

public class TimerViewModel extends ViewModel {

    private Timer timer;
    private int currentSecond;

    /**
     * 开始计时
     */
    public void startTiming(){

        if(timer == null){

            currentSecond = 0;
            timer = new Timer();
            TimerTask timerTask = new TimerTask() {
                @Override
                public void run() {
                    currentSecond ++;
                    if(onTimeChangeListener != null){
                        onTimeChangeListener.onTimeChanged(currentSecond);
                    }
                }
            };
            timer.schedule(timerTask,1000,1000);
        }
    }

    /**
     * 通过接口的方式，完成对调用者的通知
     * 实际上这种方式不是很好，更好的方式是通过LiveData组件来实现
     * 但由于我们还未学习LiveData,所以暂时采用这种方式
     */
    public interface OnTimeChangeListener{
        void onTimeChanged(int second);
    }

    private OnTimeChangeListener onTimeChangeListener;

    public void setOnTimeChangeListener(OnTimeChangeListener onTimeChangeListener) {
        this.onTimeChangeListener = onTimeChangeListener;
    }

    /**
     * 清理资源
     */
    @Override
    protected void onCleared() {
        super.onCleared();
        timer.cancel();
    }
}
